$(function() {
	increaseMaxDivideAmount();
	prepareFormInterception();
})

function increaseMaxDivideAmount() {
	var trg = $('select[name=nbtimes]').get(0);
	var opt;
	
	$([15,20,30,40,50,60,70,80,90,100,200,300,500]).each(function(k,v) {
		trg.options[ trg.options.length ] = new Option(v, v);
	});
}

function prepareFormInterception() {
	$('input[name=divide]').click(function(e) {
		if( $('select[name=nbtimes]').val() > 10 ) {
			e.preventDefault();
		} else {
			return true;
		}

		window.divide = {}
		window.divide.remainingDivides = $('select[name=nbtimes]').val();
		window.divide.attempts = 0;
		window.divide.maxAttempts = 1000;
		
		$('input[name=divide]').remove();
		$('input[name=cancel]').val('WORKING...');
		
		beginDividing(function() {
			$(document).ajaxStop(function() {
				$('input[name=cancel]').click();
			});
		});
		
		return false; 
	});
}

function beginDividing(callback) {
	var nbtimes = 10;
	if( window.divide.remainingDivides < 10 ) {
		nbtimes = window.divide.remainingDivides;
	}
	
	window.divide.attempts++;
	
	var jForm = $('form:first');
	var submitString = $('form:first').serialize().replace( /nbtimes=[0-9]+/, 'nbtimes=' + nbtimes );
	
	submitString = submitString + '&divide=divide';

	captchaAwareAjax({
		url: jForm.attr('action'),
		type: "POST",
		data: submitString,
		success: function() {
			window.divide.remainingDivides = window.divide.remainingDivides - nbtimes;
			if( window.divide.remainingDivides > 0 )
				beginDividing(callback);
			else
				callback();
		}
	});
}